package com.huxt.Link.LinkedList;

public class LinkedList<E> {

    /**
     * @author hu xiao tian
     * @description: e表示链表当前的元素，next表示该元素指向下个节点
     * @date 2021/6/13 12:56
     */
    private class Node{
        /**
         * @author hu xiao tian
         * @description: next是指向下个链表的指针，非常重要，也就是链表循环和其他节点的链接所在
         * @date 2021/6/13 13:51
         */
        public E e;
        public Node next;

        public Node(E e, Node next){
            this.e = e;
            this.next = next;
        }

        public Node(E e){
            this(e, null);
        }

        public Node(){
            this(null, null);
        }

        @Override
        public String toString(){
            StringBuilder s = new StringBuilder();
            Node cur = this;
            while(cur != null){
                s.append(cur.e + "->");
                cur = cur.next;
            }
            s.append("NULL");
            return s.toString();
        }
    }

    /**
     * @author hu xiao tian
     * @description: head表示链表的头部，size表示的是链表的个数
     * @date 2021/6/13 13:07
     */
    private Node head;
    private int size;

    public LinkedList(){
        head = null;
        size = 0;
    }

    public int getSize(){
        return size;
    }

    public boolean isEmpty(){
        return size == 0;
    }

    // 在链表头添加新的元素e
    public void addFirst(E e){
        /**
         * @author hu xiao tian
         * @description: head是头要保持一致,head当前head
         * @date 2021/6/13 13:09
         */
//        Node node = new Node(e);
//        node.next = head;
//        head = node;

        head = new Node(e, head);
        size ++;
    }

    // 在链表的index(0-based)位置添加新的元素e
    public void add(int index, E e){

        if(index < 0 || index > size)
            throw new IllegalArgumentException("Add failed. Illegal index.");

        if(index == 0)
            addFirst(e);

        else{
            Node prev = head;
            for(int i = 0 ; i < index - 1 ; i ++)
                /**
                 * @author hu xiao tian
                 * @description: index表示的是链表的索引位置，不是具体的链表值
                 *               prev.next每次循环都会从索引第一位置移动到index的前一个位置
                 * @date 2021/6/13 13:47
                 */
                prev = prev.next;

            Node node = new Node(e);
            node.next = prev.next;
            prev.next = node;

//            prev.next = new Node(e, prev.next);
            size ++;
        }
    }

    // 在链表末尾添加新的元素e
    public void addLast(E e){
        add(size, e);
    }

    @Override
    public String toString() {
        return "LinkedList{" +
                "head = " + head +
                ", size = " + size +
                '}';
    }
}
